<?php
/**
* Copyright 2009 Waag Society <http://www.waag.org>
* This file is part of Annotrax.
*
* Annotrax is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Annotrax is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Annotrax.
* If not, see http://www.gnu.org/licenses/gpl.html
*/

?>
<?php
class Admin_Model_UserMapper{
    private $dbTable;
	private $tableName = 'user_admin';

	/**
	 * find $user by id
	 * @param Admin_Model_User $user User model to find for
	 */
    public function find( Admin_Model_User $user ){
		$result = $this->getTable()->find( $user->id );

		if( null !== $result ){
			$result = $result->toArray();
			foreach( array_shift($result) as $key => $value ){
				$user->$key = $value;
			}
		}
    }

	/**
	 * find user by username
	 * @param Admin_Model_User $user User model to find for
	 */
	public function findByName( Admin_Model_User $user ){
		$result = $this->getTable()->fetchRow(
			$this->getTable()
			->select()
			->where('username = ?', $user->username )
		);

		if( null !== $result ){
			foreach( $result->toArray() as $key => $value ){
				$user->$key = $value;
			}
		}
	}

	/**
	 * Fetch all users from db
	 *
	 * @return array $users All users
	 */
	public function fetchAll(){
		$collect = array();
		$result  = $this->getTable()->fetchAll();

		if( null !== $result ){
			foreach( $result->toArray() as $key => $value ){
				$collect = new Admin_Model_User( $value );
			}
		}

		return $collect;
	}

    public function save( Admin_Model_User $user ){
		$values = array(
			'name'		=> $user->name,
			'username'	=> $user->username,
			'password'	=> $user->password,
			'email'		=> $user->email
		);

        if( null === $user->id ){
			$user->id = $this->getTable()->insert( $values );
        }
        else{
			$this->getTable()->update( $values, array( 'id =? ', $user->id ) );
        }
        return $user;
    }

	/**
	 * @return new Zend_Db_Table $table
	 */
    private function getTable(){
        if( $this->dbTable === null ){
			$dbTable = new Zend_Db_Table( array('name' => $this->tableName, 'primary' => 'id') );
			$this->setTable( $dbTable );
        }
        return $this->dbTable;
    }

    private function setTable( $dbTable ){
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->dbTable = $dbTable;
    }
}
